﻿using Lk.WebTow.Authorize;
using Lk.WebTow.Data;
using Lk.WebTow.Filter;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Unicode;

namespace Lk.WebTow
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));//全局错误过滤日志
            }).AddControllersAsServices();

            //services.AddEnyimMemcached(options => Configuration.GetSection("enyimMemcached").Bind(options));

            var connection = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connection));

            //Session
            services.AddSession();

          //  services.AddIdentityServer().AddAspNetIdentity<NcManager>();
            //Cookie(1)添加 Cookie 服务
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            ////后台管理员cookie服务
            .AddCookie(AdminAuthorizeAttribute.AdminAuthorizeAttributeScheme, options =>
            {
                options.LoginPath = "/admin/Login/Index";//登录路径
                options.LogoutPath = "/admin/Login/LogOff";//退出路径
                options.AccessDeniedPath = new PathString("/Error/Forbidden");//拒绝访问页面
                options.Cookie.Path = "/";
            })
            //前台用户cookie服务
            .AddCookie(UserAuthorizeAttribute.UserAuthenticationScheme, options =>
            {
                options.LoginPath = "/Login/Index";
                options.LogoutPath = "/Login/LogOff";
                options.AccessDeniedPath = new PathString("/Error/Forbidden");//拒绝访问页面
                options.Cookie.Path = "/";
            });

            //反转义，中文会被转义（如：浏览器上右键中文被编码）或使用@Html.Raw()反转义
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
        
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();//添加NLog //读取Nlog配置文件，这里如果是小写，文件也一定是小写，否则linux下不识别  
            env.ConfigureNLog(Path.Combine("Config", "Nlog.config"));
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseEnyimMemcached();
            //发送友好状态码页面
            app.UseStatusCodePages();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            // app.UseCookiePolicy();
            app.UseSession();
            //Cookie(2)使用Cookie的中间件
            app.UseAuthentication();
           // app.UseIdentityServer();
            app.UseMvc(routes =>
            {
                //域，配置
                routes.MapRoute(
                    name: "areaRoute",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
